package br.inf.solutions.apresentacoes.ssp.view.composer;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;

import br.com.vexillum.util.Return;
import br.inf.solutions.apresentacoes.ssp.control.bulletin.BaseItensBulletinController;
import br.inf.solutions.apresentacoes.ssp.model.bulletin.BulletinItem;
import br.inf.solutions.apresentacoes.ssp.model.interfaces.IExistsPerson;

@SuppressWarnings("serial")
public abstract class BulletinItemComposer<E extends BulletinItem, G extends BaseItensBulletinController<E>>
		extends SearchPersonComposer<E, G> {
	
	private boolean retification = false;
	
	private E itemToRetificate;

	public boolean getRetification() {
		return retification;
	}

	public void setRetification(boolean retification) {
		this.retification = retification;
	}

	public E getItemToRetificate() {
		return itemToRetificate;
	}

	public void setItemToRetificate(E itemToRetificate) {
		this.itemToRetificate = itemToRetificate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		E item = session.getAttribute("itemToRetificate") == null ? null : (E) session.getAttribute("itemToRetificate");
		session.setAttribute("itemToRetificate", null);
		if(item != null){
			setItemToRetificate(item);
			setEntity(cloneItemToRetificate());
			if(item instanceof IExistsPerson){
				setRg(item.getPerson().getRg());
			}
			setRetification(true);
		}
	}
	
	@SuppressWarnings("unchecked")
	private E cloneItemToRetificate(){
		E item = (E) getItemToRetificate().cloneEntity();
//		item.setId(null);
		return item;
	}
	
	@Override
	public Return saveEntity() {
		Return ret = super.saveEntity();
		if(getRetification() && ret.isValid()){
			Executions.sendRedirect("/paginas/retificacao/pesquisa.zul?retificado=true");
		}
		return ret;
	}

	@Override
	public Return saveEntity(Boolean transactionControlled) {
		if(getRetification()){
			return getControl().doAction("retification", transactionControlled);
		}
		return super.saveEntity(transactionControlled);
	}
	
	
}
